//
//  CSAddressViewController.m
//  CSUIKit
//
//  Created by 浙大网新中研软件 on 2017/12/29.
//

#import "CSLocalityViewController.h"
#import "CSPlaceModel.h"

#define HEIGHT_NAVIGATION_VIEW 40.0

@interface CSLocalityViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *provinceList;

//分类列表
@property (nonatomic, strong) NSMutableArray *categoryList;

@property (nonatomic, strong) NSMutableArray *sectionIndexList;

@property (nonatomic, strong) UITableView *cityTableView;//市表格
@property (nonatomic, strong) UITableView *subLocalityTableView;//区表格

@property (nonatomic, strong) NSArray *cityList;
@property (nonatomic, strong) NSArray *subLocalityList;

@property (nonatomic, strong) UIView *navigationView;

@property (nonatomic, strong) UIButton *cityButton;
@property (nonatomic, strong) UIButton *provinceButton;

/**
 * 当前GPS定位城市
 */
@property (nonatomic, strong) UIButton *currentGpsCityButton;

@end

@implementation CSLocalityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"选择行政区域";
    
    [self initData];
    [self layoutView];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/**
 * 初始化数据
 */
-(void)initData{
    
    if (self.placeList == nil) {
        return;
    }
    
    self.provinceList = [self.placeList objectAtIndex:0];//省
    NSArray *cityList = [self.placeList objectAtIndex:1];//市
    NSArray *subLocalityList = [self.placeList objectAtIndex:2];//区
    
    //市的处理
    for (int i = 0; i < cityList.count; i++) {
        
        CSPlaceModel *cityModel = [cityList objectAtIndex:i];
        
        NSString *subLocalityString = [cityModel.code getSubstringFrom:4 to:6];
        
        if (![subLocalityString isEqualToString:@"00"]) {
            continue;
        }
        
        for (int j = 0; j < self.provinceList.count; j++) {
            
            CSPlaceModel *proviceModel = [self.provinceList objectAtIndex:j];
            
            if ([[cityModel.code getSubstringFrom:0 to:2] isEqualToString:[proviceModel.code getSubstringFrom:0 to:2]]) {
                [proviceModel.subPlaces addObject:cityModel];
                break;
            }
        }
    }
    
    for (int i = 0; i < subLocalityList.count; i++) {
        
        CSPlaceModel *subLocalityModel = [subLocalityList objectAtIndex:i];
        
        for (int j = 0; j < cityList.count; j++) {
            
            CSPlaceModel *cityModel = [cityList objectAtIndex:j];
            
            if ([[subLocalityModel.code getSubstringFrom:0 to:4] isEqualToString:[cityModel.code getSubstringFrom:0 to:4]]) {
                [cityModel.subPlaces addObject:subLocalityModel];
            }
            
        }
        
    }
  
   self.categoryList = [self classifyProvince:self.provinceList];
    self.sectionIndexList = [self getIndexList:self.categoryList];
}

-(NSMutableArray *)classifyProvince:(NSMutableArray *)array{
    
    NSMutableArray *ans = [[NSMutableArray alloc] init];
    
    //比较拼音字母大小
    NSArray *serializeArray = [(NSArray *)array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {//排序
        int i;
        
        NSString *strA = ((CSPlaceModel *)obj1).pinyin.count > 0 ? [((CSPlaceModel *)obj1).pinyin objectAtIndex:0] : @"";
        NSString *strB = ((CSPlaceModel *)obj2).pinyin.count > 0 ? [((CSPlaceModel *)obj2).pinyin objectAtIndex:0] : @"";
        for (i = 0; i < strA.length && i < strB.length; i ++) {
            char a = [strA characterAtIndex:i];
            char b = [strB characterAtIndex:i];
            if (a > b) {
                return (NSComparisonResult)NSOrderedDescending;//上升
            }
            else if (a < b) {
                return (NSComparisonResult)NSOrderedAscending;//下降
            }
        }
        
        if (strA.length > strB.length) {
            return (NSComparisonResult)NSOrderedDescending;
        }else if (strA.length < strB.length){
            return (NSComparisonResult)NSOrderedAscending;
        }else{
            return (NSComparisonResult)NSOrderedSame;
        }
    }];
    
    char lastC = '1';
    NSMutableArray *data;
    NSMutableArray *oth = [[NSMutableArray alloc] init];//other
    
    for (CSPlaceModel *placeModel in serializeArray) {
        
        NSString *pinyinString = @"";
        for (int i = 0; i < placeModel.pinyin.count; i++) {
            
            pinyinString = [NSString stringWithFormat:@"%@%@", pinyinString, [placeModel.pinyin objectAtIndex:i]];
            
        }
        
        if(pinyinString.length <= 0){
            [oth addObject:placeModel];
            continue;
        }
        
        char c = [pinyinString characterAtIndex:0];
        
        if (!isalpha(c)) {//如果不是字母
            [oth addObject:placeModel];
        }
        else if (c != lastC){//如果不是同组，则新建新的一组
            lastC = c;
            if (data && data.count > 0) {
                [ans addObject:data];
            }
            
            data = [[NSMutableArray alloc] init];
            [data addObject:placeModel];
        }
        else {//如果是同组，则加上去
            [data addObject:placeModel];
        }
    }
    if (data && data.count > 0) {//字母
        [ans addObject:data];
    }
    if (oth.count > 0) {//其他
        [ans addObject:oth];
    }
    return ans;
}

-(NSMutableArray *)getIndexList:(NSMutableArray *)array{
    NSMutableArray *section = [[NSMutableArray alloc] init];
    for (NSArray *item in array) {
        CSPlaceModel *placeModel = [item objectAtIndex:0];
        if (placeModel.fullname == nil||[placeModel.fullname isEqualToString:@""]) {
            char c = '#';
            [section addObject:[NSString stringWithFormat:@"%c", toupper(c)]];
        }else{
            char c = [[placeModel.pinyin objectAtIndex:0] characterAtIndex:0];
            if (!isalpha(c)) {
                c = '#';
            }
            
            [section addObject:[NSString stringWithFormat:@"%c", toupper(c)]];
        }
    }
    return section;
}

/**
 * 布局处理
 */
-(void)layoutView{
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    CGFloat primaryY = 0;
    
    //GPS定位
    if (self.currentGpsAddress) {
        
        CS_Page_SectionTitleView *page_SectionTitleView = [CS_Page_SectionTitleView page_SectionTitleView:@"CPS定位区域" color:COLOR_TEXT_2 image:nil];
        primaryY = [page_SectionTitleView layoutView:self.view primaryY:primaryY];
        self.currentGpsCityButton.frame = CGRectMake(20, primaryY + 10, self.currentGpsCityButton.frame.size.width, 40);
        [self.view addSubview:self.currentGpsCityButton];
        primaryY += 60;
        
    }

    
    //省直辖市列表
    self.tableView.sectionIndexColor = COLOR_TEXT_3;
    self.tableView.sectionIndexBackgroundColor = [UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.frame = CGRectMake(0, primaryY, kWindowW, kWindowH - primaryY);
    [self.view addSubview:self.tableView];
}


#pragma mark --- UITableViewDelegate, UITableViewDataSource

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if(tableView == self.tableView){
        
        return ((NSArray *)[self.categoryList objectAtIndex:section]).count;
        
    }else if (tableView == self.cityTableView){
        
        return self.cityList.count;
        
    }else if (tableView == self.subLocalityTableView){
        
        return self.subLocalityList.count;
        
    }
    
    return 0;
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    if (tableView == self.tableView) {
        return self.categoryList.count;
    }else{
        return 1;
    }
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CSPlaceModel *placeModel = nil;
    
    if (tableView == self.tableView) {
        
        NSArray *sectionDatas = [self.categoryList objectAtIndex:indexPath.section];
        placeModel = [sectionDatas objectAtIndex:indexPath.row];
        
    }else if (tableView == self.cityTableView){
        
        placeModel = [self.cityList objectAtIndex:indexPath.row];
        
    }else if (tableView == self.subLocalityTableView){
        
        placeModel = [self.subLocalityList objectAtIndex:indexPath.row];
        
    }
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.font = [UIFont systemFontOfSize:FONT_SIZE_1];
    cell.textLabel.textColor = COLOR_TEXT_1;
    cell.textLabel.text = placeModel.fullname;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    return cell;
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (tableView == self.tableView) {
        id label = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"headerView"];
        if (!label) {
            label = [[UILabel alloc] init];
            [label setFont:[UIFont systemFontOfSize:14.5f]];
            [label setTextColor:[UIColor grayColor]];
            [label setBackgroundColor:COLOR_CONTROLER_SELECTED_MAIN];
        }
        [label setText:[NSString stringWithFormat:@"  %@",self.sectionIndexList[section]]];
        return label;
    }else{
        return nil;
    }
    
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    
    if (tableView == self.tableView) {
        return self.sectionIndexList;
    }else{
        return nil;
    }
    
    
}

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (tableView == self.tableView) {
        return 22.0;
    }else{
        return 0;
    }
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == self.tableView) {
        
        NSArray *array = [self.categoryList objectAtIndex:indexPath.section];
        CSPlaceModel *placeModel = [array objectAtIndex:indexPath.row];
        self.cityList = placeModel.subPlaces;
        [self.view addSubview:self.cityTableView];
        [self.cityTableView reloadData];
        [self.view addSubview:self.navigationView];
        NSString *provinceString = [NSString stringWithFormat:@"[%@]", placeModel.fullname];
        [self.provinceButton setTitle:provinceString forState:UIControlStateNormal];
        CGFloat needWidth = [self estimateWith:provinceString font:self.provinceButton.titleLabel.font height:HEIGHT_NAVIGATION_VIEW] + 20;
        self.provinceButton.frame = CGRectMake(20, 20, needWidth, HEIGHT_NAVIGATION_VIEW);
        [self.cityButton removeFromSuperview];
        
    }else if(tableView == self.cityTableView){
        
        CSPlaceModel *placeModel = [self.cityList objectAtIndex:indexPath.row];
        self.subLocalityList = placeModel.subPlaces;
        [self.view addSubview:self.subLocalityTableView];
        [self.subLocalityTableView reloadData];
        NSString *cityString = [NSString stringWithFormat:@"[%@]", placeModel.fullname];
        [self.cityButton setTitle:cityString forState:UIControlStateNormal];
        CGFloat needWidth = [self estimateWith:cityString font:self.cityButton.titleLabel.font height:HEIGHT_NAVIGATION_VIEW] + 20;
        self.cityButton.frame = CGRectMake(self.provinceButton.frame.size.width + 20 + 10, 20, needWidth, HEIGHT_NAVIGATION_VIEW);
        [self.navigationView addSubview:self.cityButton];
        
    }else if (tableView == self.subLocalityTableView){
        
        CSPlaceModel *placeModel = [self.subLocalityList objectAtIndex:indexPath.row];
        NSString *provinceString = [self.provinceButton.titleLabel.text replaceCharcter:@"[" withCharcter:@""];
        provinceString = [provinceString replaceCharcter:@"]" withCharcter:@""];
        NSString *cityString = [self.cityButton.titleLabel.text replaceCharcter:@"[" withCharcter:@""];
        cityString = [cityString replaceCharcter:@"]" withCharcter:@""];
        NSString *addressString = [NSString stringWithFormat:@"%@ %@ %@", provinceString, cityString, placeModel.fullname];
        if (self.onLocationSelectedHandler) {
            self.onLocationSelectedHandler(addressString);
        }
        [self.navigationController popViewControllerAnimated:YES];
        
    }
    
}

#pragma mark --- click handler

-(void)provinceClick{
    [self.navigationView removeFromSuperview];
    [self.cityTableView removeFromSuperview];
    [self.subLocalityTableView removeFromSuperview];
    [self.cityButton setTitle:@"" forState:UIControlStateNormal];
    [self.provinceButton setTitle:@"" forState:UIControlStateNormal];
    
}

-(void)cityClick{
    [self.subLocalityTableView removeFromSuperview];
    [self.cityButton setTitle:@"" forState:UIControlStateNormal];
    [self.cityButton removeFromSuperview];
}

-(void)currentGPSAddressClick{
    
    if (self.onLocationSelectedHandler) {
        NSString *addressString = [NSString stringWithFormat:@"%@ %@ %@", self.currentGpsAddress.administrativeArea, self.currentGpsAddress.locality, self.currentGpsAddress.subLocality];
        self.onLocationSelectedHandler(addressString);
    }
    [self.navigationController popViewControllerAnimated:YES];
    
}

#pragma mark --- Lazy layout

-(UIScrollView *)scrollView{
    
    if (_scrollView == nil) {
        _scrollView = [UIScrollView new];
    }
    return _scrollView;
    
}

-(UITableView *)tableView{
    
    if (_tableView == nil) {
        _tableView = [UITableView new];
        _tableView.dataSource = self;
        _tableView.delegate = self;
    }
    return _tableView;
    
}

-(NSMutableArray *)provinceList{
    
    if (_provinceList == nil) {
        _provinceList = [NSMutableArray new];
    }
    return _provinceList;
    
}

-(UITableView *)cityTableView{
    
    if (_cityTableView == nil) {
        
        _cityTableView = [UITableView new];
        _cityTableView.dataSource = self;
        _cityTableView.delegate = self;
        _cityTableView.frame = CGRectMake(0, HEIGHT_NAVIGATIONBAR + HEIGHT_NAVIGATION_VIEW + 30, kWindowW, HEIGHT_CONTENT - HEIGHT_NAVIGATION_VIEW - 30);
        
    }
    
    return _cityTableView;
    
}

-(UITableView *)subLocalityTableView{
    
    if (_subLocalityTableView == nil) {
        _subLocalityTableView = [UITableView new];
        _subLocalityTableView.dataSource = self;
        _subLocalityTableView.delegate = self;
        _subLocalityTableView.frame = CGRectMake(0, HEIGHT_NAVIGATIONBAR + HEIGHT_NAVIGATION_VIEW + 30, kWindowW, HEIGHT_CONTENT - HEIGHT_NAVIGATION_VIEW - 30);
    }
    return _subLocalityTableView;
    
}

-(UIView *)navigationView{
    
    if (_navigationView == nil) {
        _navigationView = [[UIView alloc] init];
        _navigationView.frame = CGRectMake(0, HEIGHT_NAVIGATIONBAR, kWindowW, HEIGHT_NAVIGATION_VIEW + 30);
        [_navigationView addSubview:self.provinceButton];
        [_navigationView addSubview:self.cityButton];
        _navigationView.backgroundColor = [UIColor whiteColor];
    }
    return _navigationView;
    
}

-(UIButton *)cityButton{
    
    if (_cityButton == nil) {
        _cityButton = [[UIButton alloc] init];
        _cityButton.frame = CGRectMake(80, 0, 80, HEIGHT_NAVIGATION_VIEW);
        [_cityButton setTitleColor:COLOR_THEME forState:UIControlStateNormal];
        _cityButton.titleLabel.font = [UIFont boldSystemFontOfSize:FONT_SIZE_1];
        _cityButton.titleLabel.textAlignment = NSTextAlignmentLeft;
        [_cityButton addTarget:self action:@selector(cityClick) forControlEvents:UIControlEventTouchUpInside];
        _cityButton.layer.borderWidth = 1.0;
        _cityButton.layer.borderColor = COLOR_TOP_SEPERATOR_LINE.CGColor;
    }
    return _cityButton;
    
}

-(UIButton *)provinceButton{
    
    if (_provinceButton == nil) {
        _provinceButton = [[UIButton alloc] init];
        _provinceButton.frame = CGRectMake(0, 0, 80, HEIGHT_NAVIGATION_VIEW);
        [_provinceButton setTitleColor:COLOR_THEME forState:UIControlStateNormal];
        _provinceButton.titleLabel.font = [UIFont boldSystemFontOfSize:FONT_SIZE_1];
        _provinceButton.titleLabel.textAlignment = NSTextAlignmentLeft;
        [_provinceButton addTarget:self action:@selector(provinceClick) forControlEvents:UIControlEventTouchUpInside];
        _provinceButton.layer.borderWidth = 1.0;
        _provinceButton.layer.borderColor = COLOR_TOP_SEPERATOR_LINE.CGColor;
    }
    return _provinceButton;
}

-(UIButton *)currentGpsCityButton{
    
    if (_currentGpsCityButton == nil) {
        _currentGpsCityButton = [[UIButton alloc] init];
        _currentGpsCityButton.titleLabel.font = [UIFont systemFontOfSize:FONT_SIZE_1];
        NSString *addressString = [NSString stringWithFormat:@"%@ %@ %@", self.currentGpsAddress.administrativeArea, self.currentGpsAddress.locality, self.currentGpsAddress.subLocality];
        [_currentGpsCityButton setTitle:addressString forState:UIControlStateNormal];
        [_currentGpsCityButton setTitleColor:COLOR_THEME forState:UIControlStateNormal];
        _currentGpsCityButton.layer.borderColor = COLOR_TOP_SEPERATOR_LINE.CGColor;
        _currentGpsCityButton.layer.borderWidth = 1.0;
        CGFloat needWidth = [self estimateWith:addressString font:_currentGpsCityButton.titleLabel.font height:50] + 20;
        _currentGpsCityButton.frame = CGRectMake(10, 10, needWidth, 40);
        [_currentGpsCityButton addTarget:self action:@selector(currentGPSAddressClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _currentGpsCityButton;
    
}
@end
